package com.simga.library.http;

import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.parser.ParserConfig;
import com.simga.library.utils.LogUtil;

import java.io.IOException;
import java.lang.reflect.Type;

import okhttp3.ResponseBody;
import retrofit2.Converter;

final class FastJsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {

    private static final Feature[] EMPTY_SERIALIZER_FEATURES = new Feature[0];

    private Type mType;

    private ParserConfig config;
    private int featureValues;
    private Feature[] features;

    FastJsonResponseBodyConverter(Type type, ParserConfig config, int featureValues,
                                  Feature... features) {
        this.mType = type;
        this.config = config;
        this.featureValues = featureValues;
        this.features = features;
    }

    @Override
    public T convert(ResponseBody value) throws IOException {
        String json = value.string();
        Log.e("ResponseBody ", json);
        Response temp = JSON.parseObject(json, Response.class);
        if (temp == null || temp.getCode() == -10086) {
            throw new APIException(String.valueOf(-10086), "后台出现错误");
        }
        if (!temp.isCodeInvalid()) {
            throw new APIException(String.valueOf(temp.getCode()), temp.getMessage());
        }
        if (temp.getCode() == 2000000 && temp.getData() == null) {
            throw new APIException("1015", temp.getMessage());
        }
        try {
            json = temp.getData().toString();
            return JSON.parseObject(json, mType, config, featureValues,
                    features != null ? features : EMPTY_SERIALIZER_FEATURES);
        } catch (Exception e) {
            return (T) json;
        } finally {
            value.close();
        }
    }
}
